package com.hongxun.budget.ui.fragment.tk;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DDeviceBuyEntityDao;
import com.hongxun.budget.greendao.DDeviceOldEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.fragment.BaseListFragment;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BDeviceEntity;
import com.hongxun.greenentity.tk.DDeviceBuyEntity;
import com.hongxun.greenentity.tk.DDeviceOldEntity;
import com.hongxun.greenentity.tk.DPointEntity;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2018/8/16.
 */

public class LineDeviceFragment extends BaseListFragment implements RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    int select = 0;
    //新增设备数据
    List<DDeviceBuyEntity> addDatas = new ArrayList<>();
    SuperAdapter<DDeviceBuyEntity> addAdapter;
    List<DDeviceBuyEntity> addDeleteDatas = new ArrayList<>();
    //拆除设备数据
    List<DDeviceOldEntity> ccEntities = new ArrayList<>();
    SuperAdapter<DDeviceOldEntity> ccAdapter;
    List<DDeviceOldEntity> ccDeleteEntities = new ArrayList<>();
    //修理设备数据
    List<DDeviceOldEntity> xlEntities = new ArrayList<>();
    SuperAdapter<DDeviceOldEntity> xlAdapter;
    List<DDeviceOldEntity> xlDeleteEntities = new ArrayList<>();

    @Override
    protected int getMyListLayoutId() {
        return R.layout.fragment_line_device;
    }

    @Override
    public void initView() {
        super.initView();
        initData();
        String process = (String) SPUtils.get(context, "process", "");
        select = process.equals("新增") ? 0 : process.equals("拆除") ? 1 : 2;
        set(select);
        radioGroup.check(select == 0 ? R.id.radioButton1 : select == 1 ? R.id.radioButton2 : R.id.radioButton3);
        radioGroup.setOnCheckedChangeListener(this);
    }

    private void initData() {
        addDatas.addAll(DBUtils.getDDeviceBuyEntities(context));
        addAdapter.setData(addDatas);
        addAdapter.setEmptyDataView(R.layout.view_empty);
        ccEntities.addAll(DBUtils.getDDeviceCcOldEntities(context));
        ccAdapter.setData(ccEntities);
        ccAdapter.setEmptyDataView(R.layout.view_empty);
        xlEntities.addAll(DBUtils.getDDeviceXlOldEntities(context));
        xlAdapter.setData(xlEntities);
        xlAdapter.setEmptyDataView(R.layout.view_empty);
    }

    @Override
    public SuperAdapter getAdapter() {
        addAdapter = new SuperAdapter<DDeviceBuyEntity>(R.layout.content_fragment_line_device) {
            @Override
            public void bindView(ViewHolder viewHolder, final DDeviceBuyEntity dDeviceBuyEntity, final int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(dDeviceBuyEntity.getDBName());
                ((TextView) viewHolder.getView(R.id.type)).setText(dDeviceBuyEntity.getDLabel());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(dDeviceBuyEntity.getDBParameter());
                ((TextView) viewHolder.getView(R.id.mid_type)).setText(dDeviceBuyEntity.getDBMidtype());
                ((TextView) viewHolder.getView(R.id.end_txt)).setText("数量: ");
                viewHolder.getView(R.id.option_layout).setVisibility(View.GONE);
                ((TextView) viewHolder.getView(R.id.option)).setText(dDeviceBuyEntity.getDBCount() + "");
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//删除
                        addDatas.remove(dDeviceBuyEntity);
                        addAdapter.notifyDataSetChanged();
                        addDeleteDatas.add(dDeviceBuyEntity);
                    }
                });
                viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//编辑
                        if (dDeviceBuyEntity.getDBName().startsWith("(利旧)")) {
                            T.showLong(context, "利旧设备不能编辑");
                            return;
                        }
                        DBUtils.editBuyDevice(LineDeviceFragment.this, i, dDeviceBuyEntity, 3);
                    }
                });
            }
        };
        ccAdapter = new SuperAdapter<DDeviceOldEntity>(R.layout.content_fragment_line_device) {
            @Override
            public void bindView(ViewHolder viewHolder, final DDeviceOldEntity dDeviceOldEntity, final int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(dDeviceOldEntity.getDRName());
                ((TextView) viewHolder.getView(R.id.type)).setText(dDeviceOldEntity.getDLabel());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(dDeviceOldEntity.getDRParameter());
                ((TextView) viewHolder.getView(R.id.mid_type)).setText(dDeviceOldEntity.getDRMidtype());
                viewHolder.getView(R.id.option_layout).setVisibility(View.VISIBLE);
                if (dDeviceOldEntity.getDROpinion().equals("-9")) {
                    ((TextView) viewHolder.getView(R.id.option)).setText("本项目利旧");
                } else {
                    ((TextView) viewHolder.getView(R.id.option)).setText(DBUtils.getBDataDictionaryEntity("opinion_type", dDeviceOldEntity.getDROpinion()).getDValue());
                }
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//删除
                        if (dDeviceOldEntity.getDROpinion().equals("-9")) {
                            T.showLong(context, "该设备已被利旧，不能删除");
                            return;
                        }
                        ccEntities.remove(dDeviceOldEntity);
                        ccAdapter.notifyDataSetChanged();
                        ccDeleteEntities.add(dDeviceOldEntity);
                    }
                });
                viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//编辑
                        if (dDeviceOldEntity.getDROpinion().equals("-9")) {
                            T.showLong(context, "该设备已被利旧，不能编辑");
                            return;
                        }
                        DBUtils.editOldDevice(LineDeviceFragment.this, i, dDeviceOldEntity, 2);
                    }
                });
            }
        };
        xlAdapter = new SuperAdapter<DDeviceOldEntity>(R.layout.content_fragment_line_device) {
            @Override
            public void bindView(ViewHolder viewHolder, final DDeviceOldEntity dDeviceOldEntity, final int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(dDeviceOldEntity.getDRName());
                ((TextView) viewHolder.getView(R.id.type)).setText(dDeviceOldEntity.getDLabel());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(dDeviceOldEntity.getDRParameter());
                ((TextView) viewHolder.getView(R.id.mid_type)).setText(dDeviceOldEntity.getDRMidtype());
                viewHolder.getView(R.id.option_layout).setVisibility(View.GONE);
                ((TextView) viewHolder.getView(R.id.option)).setText(DBUtils.getBDataDictionaryEntity("opinion_type", dDeviceOldEntity.getDROpinion()).getDValue());
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//删除
                        xlEntities.remove(dDeviceOldEntity);
                        xlAdapter.notifyDataSetChanged();
                        xlDeleteEntities.add(dDeviceOldEntity);
                    }
                });
                viewHolder.getView(R.id.edit_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//编辑
                        DBUtils.editOldDevice(LineDeviceFragment.this, i, dDeviceOldEntity, 2);
                    }
                });
            }
        };
        return select == 0 ? addAdapter : select == 1 ? ccAdapter : xlAdapter;
    }

    @OnClick(R.id.add_button)
    public void onViewClicked() {
        DBUtils.addDevice(this, select == 0 ? "新增" : select == 1 ? "拆除" : "大修", 1);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.radioButton1:
                select = 0;
                break;
            case R.id.radioButton2:
                select = 1;
                break;
            case R.id.radioButton3:
                select = 2;
                break;
        }
        set(select);
    }

    private void set(int i) {
        switch (i) {
            case 0:
                list.setAdapter(addAdapter);
                addAdapter.notifyDataSetChanged();
                break;
            case 1:
                list.setAdapter(ccAdapter);
                ccAdapter.notifyDataSetChanged();
                break;
            case 2:
                list.setAdapter(xlAdapter);
                xlAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case 1://选择设备
                    BDeviceEntity b = (BDeviceEntity) data.getSerializableExtra("device");
                    setChoiceData(b);
                    break;
                case 2://编辑旧设备
                    int index = data.getIntExtra("index", 0);
                    DDeviceOldEntity d = (DDeviceOldEntity) data.getSerializableExtra("device");
                    if (select == 1) {
                        ccEntities.remove(index);
                        ccEntities.add(index, d);
                        ccAdapter.notifyDataSetChanged();
                    } else {
                        xlEntities.remove(index);
                        xlEntities.add(index, d);
                        xlAdapter.notifyDataSetChanged();
                    }
                    break;
                case 3://编辑新设备
                    int i = data.getIntExtra("index", 0);
                    DDeviceBuyEntity dd = (DDeviceBuyEntity) data.getSerializableExtra("device");
                    addDatas.remove(i);
                    addDatas.add(i, dd);
                    addAdapter.notifyDataSetChanged();
                    break;
                case 4:
                    DPointEntity dPointEntity = (DPointEntity) data.getSerializableExtra("point");
                    if (!dPointEntity.getPPName().equals((String) SPUtils.get(context, "point_name", ""))) {
                        T.showLong(context, "请复制相同点位的设备。");
                        return;
                    }
                    if (dPointEntity.getGuid().equals((String) SPUtils.get(context, "UUID", ""))) {
                        T.showLong(context, "请选择其他相同点位。");
                        return;
                    }
                    copyPoint(dPointEntity);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void copyPoint(DPointEntity d) {
        DaoSession session = GreenDaoManager.getInstance().getmDaoSession();
        List<DDeviceBuyEntity> list = session.getDDeviceBuyEntityDao().queryBuilder()
                .where(DDeviceBuyEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DDeviceBuyEntityDao.Properties.PPGuid.eq(d.getGuid()), DDeviceBuyEntityDao.Properties.DBDatastate.notEq("删除")).list();
        for (DDeviceBuyEntity buy : list) {
            if (buy.getDBName().startsWith("(利旧)")) {
                T.showLong(context, "该点位包含利旧设备,无法复制。");
                return;
            }
        }
        List<DDeviceOldEntity> list2 = session.getDDeviceOldEntityDao().queryBuilder()
                .where(DDeviceOldEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DDeviceOldEntityDao.Properties.PPGuid.eq(d.getGuid()), DDeviceOldEntityDao.Properties.DRDatastate.notEq("删除")
                        , DDeviceOldEntityDao.Properties.DRWork.eq("拆除")).list();
        List<DDeviceOldEntity> list3 = session.getDDeviceOldEntityDao().queryBuilder()
                .where(DDeviceOldEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , DDeviceOldEntityDao.Properties.PPGuid.eq(d.getGuid()), DDeviceOldEntityDao.Properties.DRDatastate.notEq("删除")
                        , DDeviceOldEntityDao.Properties.DRWork.eq("修理")).list();
        for (DDeviceBuyEntity buy : list) {
            BDeviceEntity load = session.getBDeviceEntityDao().load(buy.getDDGuid());
            DDeviceBuyEntity dDeviceBuyEntity = DBUtils.setAddDevice(context, null, load, false);
            addDatas.add(dDeviceBuyEntity);
        }
        for (DDeviceOldEntity cc : list2) {
            BDeviceEntity load = session.getBDeviceEntityDao().load(cc.getDDGuid());
            DDeviceOldEntity dDeviceOldEntity = DBUtils.setOldDevice(context, null, load, "拆除", false);
            dDeviceOldEntity.setDROpinion(cc.getDROpinion().equals("-9") ? "10" : cc.getDROpinion());
            ccEntities.add(dDeviceOldEntity);
        }
        for (DDeviceOldEntity xl : list3) {
            BDeviceEntity load = session.getBDeviceEntityDao().load(xl.getDDGuid());
            DDeviceOldEntity dDeviceOldEntity = DBUtils.setOldDevice(context, null, load, "修理", false);
            dDeviceOldEntity.setDROpinion(xl.getDROpinion());
            xlEntities.add(dDeviceOldEntity);
        }
        if (select == 0) {
            addAdapter.notifyDataSetChanged();
        } else if (select == 1) {
            ccAdapter.notifyDataSetChanged();
        } else {
            xlAdapter.notifyDataSetChanged();
        }
    }

    private void setChoiceData(BDeviceEntity b) {
        if (select == 0) {
            if (b.getDName().startsWith("(利旧)")) {
                for (DDeviceBuyEntity d : addDatas) {
                    if (d.getDDGuid().equals(b.getGuid()) && d.getDBName().startsWith("(利旧)")) {
                        T.showLong(context, "该利旧设备已选择，请重新选择");
                        return;
                    }
                }
            }
            addDatas.add(DBUtils.setAddDevice(context, null, b, false));
            addAdapter.notifyDataSetChanged();
        } else if (select == 1) {
            ccEntities.add(DBUtils.setOldDevice(context, null, b, "拆除", false));
            ccAdapter.notifyDataSetChanged();
        } else if (select == 2) {
            xlEntities.add(DBUtils.setOldDevice(context, null, b, "修理", false));
            xlAdapter.notifyDataSetChanged();
        }
    }


    public void insertDB() {
        for (DDeviceBuyEntity d : addDeleteDatas) {//删除的只删除工程量
            DBUtils.deleteCost(context, d.getGuid());
            d.setDBDatastate("删除");
            if (d.getDBName().startsWith("(利旧)")) {
                DDeviceOldEntity oldEntity = GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().load(d.getDDGuid());
                oldEntity.setDROpinion("10");
                oldEntity.setDRDatastate("修改");
                GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().update(oldEntity);
            }
        }

        for (DDeviceBuyEntity d : addDatas) {
            //先删除存在的工程量信息,再插入新的工程量信息
            DBUtils.deleteCost(context, d.getGuid());
            //添加新设备工程量 1-安装 2-拆除 3-更换
            if (d.getDBName().startsWith("(利旧)")) {
                DDeviceOldEntity oldEntity = GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().load(d.getDDGuid());
                DBUtils.addDeviceCost(context, oldEntity.getDDGuid(), d.getGuid(), d.getDBName(), 0, 2, 1, Double.valueOf(d.getDBCount()));
                oldEntity.setDROpinion("-9");//设备为已使用
                oldEntity.setDRDatastate("修改");
                GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().update(oldEntity);
            } else {
                DBUtils.addDeviceCost(context, d.getDDGuid(), d.getGuid(), d.getDBName(), 0, 2, 1, Double.valueOf(d.getDBCount()));
            }
        }
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceBuyEntityDao().updateInTx(addDeleteDatas);
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceBuyEntityDao().insertOrReplaceInTx(addDatas);
        for (DDeviceOldEntity d : ccEntities) {//拆除或大修设备数量为1
            DBUtils.deleteCost(context, d.getGuid());
            DBUtils.addDeviceCost(context, d.getDDGuid(), d.getGuid(), d.getDRName(), 0, 1, 2
                    , 1.0);
        }
        for (DDeviceOldEntity d : ccDeleteEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            d.setDRDatastate("删除");
        }
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().insertOrReplaceInTx(ccEntities);
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().updateInTx(ccDeleteEntities);

        for (DDeviceOldEntity d : xlEntities) {//拆除或大修设备数量为1
            DBUtils.deleteCost(context, d.getGuid());
            DBUtils.addDeviceCost(context, d.getDDGuid(), d.getGuid(), d.getDRName(), 0, 1, 3
                    , 1.0);
        }
        for (DDeviceOldEntity d : xlDeleteEntities) {
            DBUtils.deleteCost(context, d.getGuid());
            d.setDRDatastate("删除");
        }
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().insertOrReplaceInTx(xlEntities);
        GreenDaoManager.getInstance().getmDaoSession().getDDeviceOldEntityDao().updateInTx(xlDeleteEntities);
    }
}
